<#
# 使用事例：
# 在目标目录执行脚本


#>
# 脚本参数定义
param(
    [Parameter(Mandatory=$false)]
    # 使用 [switch] 类型表示布尔开关（无需值）
    [switch]$Test

    # 参数1
)

# 检查是否有某命令
function which ($command) {
  Get-Command -Name $command -ErrorAction SilentlyContinue |
    Select-Object -ExpandProperty Path -ErrorAction SilentlyContinue
}

function XWrite-Host ($FLAG,$String) {
    # $NowDateTime = $(Get-Date -f "MM-dd HH:mm:ss")
    $NowDateTime = $(Get-Date -f "HH:mm:ss")
    if ($Test) {# 传递了 --test 参数
        switch($FLAG){
        # switch -Wildcard ( $FLAG ){
            # 'Info' { 
            #     Write-Information "[$FLAG][$NowDateTime] $String ."   
            # }
            { $_ -in "Info", "INFO" } {
                # Write-Information "[$FLAG][$NowDateTime] $String ." 
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Blue 
            }
            { $_ -in "EARNING", "Warning" } { 
                # Write-Warning -Message "[$FLAG][$NowDateTime] $String ."  
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Yellow  
            }
            { $_ -in "Debug", "DEBUG" } { 
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Blue 
            }
            { $_ -in "Error", "ERROR" } { 
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Red 
                # Write-Error -Message "[$FLAG][$NowDateTime] $String ." 
            }
            default { Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Green }
        }
    } else {
        switch($FLAG){
            { $_ -in "Info", "INFO" }  {
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Blue 
            }
            { $_ -in "Error", "ERROR" } { 
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Red 
            }
            default { 
                # Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Green 
            }
        }
    }
}

# [关于编码：使用PowerShell以UTF-8编写没有BOM的文件 | 码农家园](https://www.codenong.com/5596982/)
function Out-FileUtf8NoBom {

    [CmdletBinding()]
    param(
      [Parameter(Mandatory, Position=0)] [string] $LiteralPath,
      [switch] $Append,
      [switch] $NoClobber,
      [AllowNull()] [int] $Width,
      [Parameter(ValueFromPipeline)] $InputObject
    )
  
    #requires -version 3
  
    # Make sure that the .NET framework sees the same working dir. as PS
    # and resolve the input path to a full path.
    [System.IO.Directory]::SetCurrentDirectory($PWD) # Caveat: .NET Core doesn't support [Environment]::CurrentDirectory
    $LiteralPath = [IO.Path]::GetFullPath($LiteralPath)
  
    # If -NoClobber was specified, throw an exception if the target file already
    # exists.
    if ($NoClobber -and (Test-Path $LiteralPath)) {
      Throw [IO.IOException]"The file '$LiteralPath' already exists."
    }
  
    # Create a StreamWriter object.
    # Note that we take advantage of the fact that the StreamWriter class by default:
    # - uses UTF-8 encoding
    # - without a BOM.
    $sw = New-Object IO.StreamWriter $LiteralPath, $Append
  
    $htOutStringArgs = @{}
    if ($Width) {
      $htOutStringArgs += @{ Width = $Width }
    }
  
    # Note: By not using begin / process / end blocks, we're effectively running
    #       in the end block, which means that all pipeline input has already
    #       been collected in automatic variable $Input.
    #       We must use this approach, because using | Out-String individually
    #       in each iteration of a process block would format each input object
    #       with an indvidual header.
    try {
      $Input | Out-String -Stream @htOutStringArgs | % { $sw.WriteLine($_) }
    } finally {
      $sw.Dispose()
    }
  
}
#-------------------------------    Functions END     -------------------------------



function main(){
    # # 定义需要检查的参数名称
    # $parametersToCheck = @('SaveFileName', 'httpUrl')
    # $missingParams = @()

    # # 遍历检查每个参数
    # foreach ($paramName in $parametersToCheck) {
    #     $value = Get-Variable -Name $paramName -ValueOnly
    #     if ([string]::IsNullOrEmpty($value)) {
    #         $missingParams += $paramName
    #     }
    # }

    # # 提示并退出
    # $allMissingParams = $missingParams -join ', '
    # if ($missingParams.Count -gt 0) {
    #     XWrite-Host "Error" "The following parameters cannot be empty `: $allMissingParams"
    #     Write-Host "Example`:" -ForegroundColor Green
    #     # Write-Host "urldl  DiyName1   https`://xxxx.com/xxxx.m3u8" -ForegroundColor Green
    #     # Write-Host "urldl  DiyName2   https`://xxxx.com/xxxx.html" -ForegroundColor Green
    #     # Write-Host "urldl -Test  DiyName2   https`://xxxx.com/xxxx.html" -ForegroundColor Green

    #     exit 1
    # } else {
    #     # 程序入口
    # }

    ## 判断是否存在
    # ~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
    # 存在则备份并新建一个新的，并写入
    $Powershell_config_file_path = "${env:USERPROFILE}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
    #echo "[debug] file_path = $file_path"
    # 判断是否下载完成存在文件，存在则进行解压
    $TRUE_FALSE=(Test-Path $Powershell_config_file_path)
    if($TRUE_FALSE -eq "True") { 
        # 文件存在
        Write-Host "[INFO] $Powershell_config_file_path  is exits."
        # 备份
        Rename-Item -Path "$Powershell_config_file_path" -NewName "$Powershell_config_file_path-bak-$(Get-Date -f 'yyMMddHHmmss').ps1"
    } else {
        # 文件不存在
        Write-Host "[INFO] $Powershell_config_file_path It is not exits."
        # Write-Host "invoke-expression -Command C:\Users\Alice\Documents\XWorkSpaces\my-windows-config\windows-terminal\Microsoft.PowerShell_profile.ps1 " > "$Powershell_config_file_path"
    }
    # 创建文件并写入内容
    # $PSScriptRoot # 获取当前文件路径
    $Powershell_Origin_config_file_path = "$PSScriptRoot\Microsoft.PowerShell_profile.ps1"
    Write-Host "[INFO] Powershell_Origin_config_file_path = $Powershell_Origin_config_file_path."
    # 方式一： 导入 注此种写入方式无法在外面调用函数
    # # echo "invoke-expression -Command $Powershell_Origin_config_file_path " > "$Powershell_config_file_path"
    # echo "invoke-expression -Command $Powershell_Origin_config_file_path " | Out-FileUtf8NoBom  $Powershell_config_file_path
    # # Write-Host "invoke-expression -Command $Powershell_Origin_config_file_path " | Out-File  -Append  $Powershell_config_file_path
    # 方式二：导入写法2 
    # echo ". $Powershell_Origin_config_file_path " | Out-FileUtf8NoBom  $Powershell_config_file_path
    
    # echo ". $Powershell_Origin_config_file_path `n . $PSScriptRoot\initEnv.ps1 -Test" | Out-FileUtf8NoBom  $Powershell_config_file_path
    # echo ". $Powershell_Origin_config_file_path `n . $PSScriptRoot\initEnv-V1.ps1" | Out-FileUtf8NoBom  $Powershell_config_file_path
    # echo ". $Powershell_Origin_config_file_path `n . $PSScriptRoot\initEnv-V2.ps1" | Out-FileUtf8NoBom  $Powershell_config_file_path
    echo ". $Powershell_Origin_config_file_path " | Out-FileUtf8NoBom  $Powershell_config_file_path

    # 
    # 设置git提示字体编码
    git config --global core.quotepath false  
    git config --global gui.encoding utf-8  
    git config --global i18n.commit.encoding utf-8  
    git config --global i18n.logoutputencoding utf-8  

    # 判断是否powershell 7 有的话
    $Powershell7_config_file_path = "${env:USERPROFILE}\Documents\PowerShell\Microsoft.PowerShell_profile.ps1"
    # 存在则备份并新建一个新的，并写入
    # 判断是否下载完成存在文件，存在则进行解压
    $TRUE_FALSE=(Test-Path $Powershell7_config_file_path)
    if($TRUE_FALSE -eq "True") { 
        # 文件存在
        Write-Host "[INFO] $Powershell7_config_file_path  is exits."
        # 备份
        Rename-Item -Path "$Powershell7_config_file_path" -NewName "$Powershell7_config_file_path-bak-$(Get-Date -f 'yyMMddHHmmss').ps1"
    } else {
        # 文件不存在
        Write-Host "[INFO] $Powershell7_config_file_path It is not exits."
    }
    # 创建文件并写入内容
    # $PSScriptRoot # 获取当前文件路径
    $Powershell7_Origin_config_file_path = "$PSScriptRoot\Microsoft.PowerShell_profile.ps1"
    Write-Host "[INFO] Powershell7_Origin_config_file_path = $Powershell7_Origin_config_file_path."
    # 导入写法2 
    echo ". $Powershell7_Origin_config_file_path " | Out-FileUtf8NoBom  $Powershell7_config_file_path

}


# 检查是否传递了 --test 参数
if ($Test) {
    # Write-Host "测试模式"
    Write-Host "Test Mode"
    main
} else {
    Write-Host "Normal Mode"
    main
}